package com.summer.Thread.threadSafe.Thread;

public class SellTicketWindow  extends Thread{
    private static int ticket = 100;
    private static Object object = new Object();
//    @Override
//    public void run() {
//        while (true){
//            if (ticket <= 0) break;
//            else {
//                System.out.println(Thread.currentThread().getName()+"---出票成功---票号为:"+ticket);
//                ticket--;
//            }
//        }
//    }
//第一种同步代码块解决线程安全问题
@Override
public void run() {
    while (true){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (object){
            object.notify();
        if (ticket <= 0) break;
        else {
                System.out.println(Thread.currentThread().getName()+"---出票成功---票号为:"+ticket);
                ticket--;
            }
            try {
                object.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
    //第二种同步方法解决线程安全
//@Override
//public void run() {
//    while (ticket>0){
//        try {
//            sell();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//    }
//}
//    public static synchronized void sell() throws InterruptedException {
//        if (ticket>0){
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"---出票成功---票号为:"+ticket);
//            ticket--;
//        }
//    }
    public static void main(String[] args) {
        SellTicketWindow window1 = new SellTicketWindow();
        SellTicketWindow window2 = new SellTicketWindow();
        SellTicketWindow window3 = new SellTicketWindow();
        window1.setName("窗口1");
        window2.setName("窗口2");
        window3.setName("窗口3");
        window2.start();
        window3.start();
        window1.start();
    }
}
